<template>
  <view class="container">
    <!-- 顶部流程展示 -->
    <message-step></message-step>
    <!-- 表单内容 -->
    <view class="form-content">
      <uni-forms ref="form" :modelValue="formData" :rules="rules">
        <!-- 必填项说明 -->
        <view class="form-tip">请您填写请假申批资料，带*号为必填项</view>
        
        <uni-forms-item label="处理原因" required name="reason">
          <uni-easyinput
            :disabled="isReadonly"
            v-model="formData.reason"
            type="textarea"
            placeholder="请填写处理原因"
            maxlength="500"
            :inputBorder="true"
          />
          <text class="counter">{{formData.reason.length}}/500</text>
        </uni-forms-item>
        
        <uni-forms-item label="开始时间" required name="startTime">
          <uni-datetime-picker
            v-model="formData.startTime"
            type="datetime"
            :clear-icon="false"
            @change="onStartDateChange"
          />
        </uni-forms-item>
        
        <uni-forms-item label="结束时间" required name="endTime">
          <uni-datetime-picker
            v-model="formData.endTime"
            type="datetime"
            :clear-icon="false"
            @change="onEndDateChange"
          />
        </uni-forms-item>
      </uni-forms>
    </view>

    <!-- 提交按钮 -->
    <view>
      <view class="submit-btn" @tap="submitForm">
        提交申批申请
      </view>
    </view>
  </view>
</template>

<script>
  import {formatTime} from '../../utils/format.js'
  export default {
    data() {
      return {
        mode: '',
        pendingName: '',
        type: 0,
        isReadonly : false,
        timer: null,
        query: {},
        formData: {
          reason: '',
          startTime: '',
          endTime: '',
        },
        FormData2: {
          type: 0,
        },
        DetailMessage: {},
        rules: {
            reason: {
              rules: [{
                required: true,
                errorMessage: '请输入处理原因'
              }]
            },
            startTime: {
              rules: [{
                required: true,
                errorMessage: '请选择开始时间'
              }]
            },
            endTime: {
              rules: [{
                required: true,
                errorMessage: '请选择结束时间'
              }]
            }
          }
      };
    },
    onLoad(options) {
      if(options.item !== '{}' && options.item) {
        this.DetailMessage = JSON.parse(options.item)
        this.isReadonly = true
        this.getOriginalData()
        this.type = this.DetailMessage.type
        this.mode = this.DetailMessage.mode
      }else {
        this.query = options
        this.FormData2.type = Number(options.type)
        uni.setNavigationBarTitle({
          title:this.query.title
        })
      }
    },
    methods: {
      onStartDateChange(e) {
        this.formData.startTime = formatTime(e)
      },
      onEndDateChange(e) {
        this.formData.endTime = formatTime(e)
      },
      // 回显数据
      getOriginalData(){
        this.formData = {
          reason: this.DetailMessage.reason,
          startTime: this.DetailMessage.startTime,
          endTime: this.DetailMessage.endTime,
        }
      },
      // 添加防抖函数
      debounce(fn, delay = 500) {
        if (this.timer) {
          clearTimeout(this.timer)
          // 如果定时器存在，说明用户频繁点击
          uni.$showMsg('你手速也太快了吧，距离上次提交还不过1秒')
          return
        }
        this.timer = setTimeout( () => {
          fn()
          this.timer = null
        }, delay)
      },
      
      // 修改提交表单函数,添加了更新如果是销假状态或者延假状态不合理的状态的提示
      async submitForm() {
        // 校验表单内容
        await this.$refs.form.validate()
        uni.showLoading({
          title: '提交中',
          mask: true
        });
        this.debounce(async () => {
          try {
            if(this.mode === 'extend') {
              if(this.formData.startTime === this.DetailMessage.startTime ) {
                this.formData.startTime = formatTime(this.formData.startTime)
              } 
              if(this.formData.endTime === this.DetailMessage.endTime) {
                 this.formData.endTime = formatTime(this.formData.endTime)
              }
              console.log(this.type,this.formData.startTime,this.formData.endTime)
              await uni.$http.patch(`/attendance/leaveRecord/${this.DetailMessage.id}`,{
                type: this.type,
                startTime: this.formData.startTime,
                endTime: this.formData.endTime
              })
              uni.$showMsg('修改完成!!!')
              return uni.reLaunch({
                url: '/pages/application/application'
              })
            }
            // 合并表单数据
            const formDataTo = {...this.FormData2, ...this.formData}
            // 发送请求
            await uni.$http.post('/attendance/leave', formDataTo)
            uni.hideLoading()
            // 提示成功
            uni.$showMsg('提交成功,请耐心等待部门审批',2000)
            
            // 可以添加成功后的跳转
            setTimeout(() => {
              uni.reLaunch({
                url: '/pages/sumbit/sumbit'
              })
            },3000)
          // 这里添加try-catch的逻辑
          }catch(error) {
            uni.hideToast();  // 关闭提示框的方法
            uni.$showModal({content: '审核失败,请你耐心检查一下,是不是该申请信息已经失效,失效的话，请不要再次尝试了'})
          }
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
.container {
  padding: 20rpx;
  background: linear-gradient(180deg,#2b7ff3 0%,#f5f5f5 100%);
  min-height: 100vh;
}

.form-content {
  margin-top: 20rpx;
  background-color: #fff;
  border-radius: 10rpx;
  padding: 20rpx;
  font-weight: bold;
  
  .form-tip {
    color: #999;
    font-size: 24rpx;
    margin-bottom: 20rpx;
  }
  
  .counter {
    position: absolute;
    right: 10rpx;
    bottom: 10rpx;
    font-size: 24rpx;
    color: #999;
  }
}

.submit-btn {
  // position: fixed;
  // bottom: 40rpx;
  // left: 20rpx;
  // right: 20rpx;
  height: 80rpx;
  margin-top: 20rpx;
  background-color: #007AFF;
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 8rpx;
  font-size: 32rpx;
}
</style> 
